package com.lp.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.model.config.AppResult;
import com.lp.model.config.CodeMsg;
import com.lp.model.constants.HeaderConstants;
import com.lp.model.constants.RedisConstants;
import com.lp.model.dto.user.UserLoginDto;
import com.lp.model.dto.user.UserRegDto;
import com.lp.model.entity.user.User;
import com.lp.model.entity.user.Userinfo;
import com.lp.model.entity.user.vo.UserVO;
import com.lp.model.entity.user.vo.UserinfoVO;
import com.lp.user.service.IUserService;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 登录
     * @param loginDto 用户名、密码
     */
    @PostMapping("/login")
    public AppResult login(@RequestBody @NonNull UserLoginDto loginDto) {
        if(!StringUtils.hasLength(loginDto.getPassword()) || !StringUtils.hasLength(loginDto.getUsername())) {
            return AppResult.fail(CodeMsg.FAIL_NULL_USER);
        }
        //登录成功, 获取 token
        String token = userService.login(loginDto);
        return AppResult.success(CodeMsg.SUCCESS, token);
    }

    /**
     * 注册
     * @param regDto 用户名、密码、昵称
     */
    @PostMapping("/reg")
    public AppResult reg(@RequestBody @NonNull UserRegDto regDto) {
        if(!StringUtils.hasLength(regDto.getNickname()) || !StringUtils.hasLength(regDto.getUsername()) ||
                !StringUtils.hasLength(regDto.getPassword())) {
            return AppResult.fail(CodeMsg.FAIL_NULL_USER);
        }
        userService.reg(regDto);
        return AppResult.success(CodeMsg.SUCCESS);
    }

    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //1.获取 token 数据
        String token = request.getHeader(HeaderConstants.TOKEN);
        //2.退出登录
        userService.logout(token);
        return AppResult.success();
    }

    /**
     * 通过 id 获取用户信息
     * @return
     */
    @GetMapping("/info")
    public AppResult info(@NonNull Long id) {
        return AppResult.success(userService.getUserById(id));
    }

    /**
     * 获取当前用户信息
     * @param request 从中获取 token
     */
    @GetMapping("/cur_info")
    public AppResult curInfo(HttpServletRequest request) {
        //1.获取 token
        String token = request.getHeader(HeaderConstants.TOKEN);
        //2.解析并整合统计信息
        UserVO curUserinfo = userService.getCurUserVO(token);
        return AppResult.success(curUserinfo);
    }

    /**
     * 根据用户名获取用户所有信息
     * @param username
     * @return
     */
    @GetMapping("/userinfo_vo")
    public AppResult userinfoVO(@NonNull String username) {
        UserinfoVO userinfoVOByUsername = userService.getUserinfoVOByUsername(username);
        return AppResult.success(userinfoVOByUsername);
    }

    @SneakyThrows
    @PostMapping("/update_user")
    public AppResult updateUser(HttpServletRequest request, @RequestBody @NonNull User user) {
        //1.非空校验(可修改的数据至少有一个不为空)
        if(user.getNickname() == null && user.getBrief() == null
                && user.getPassword() == null) {
            return AppResult.fail(CodeMsg.FAIL_NULL_USER_UPDATE);
        }
        //2.准备数据(用户 id 和 token)
        String token = request.getHeader(HeaderConstants.TOKEN);
        String userJson = redisTemplate.opsForValue().get(RedisConstants.TOKEN + token);
        User redisUser = objectMapper.readValue(userJson, User.class);
        user.setId(redisUser.getId());
        //3.修改
        userService.update(user, token);
        return AppResult.success();
    }

    @SneakyThrows
    @PostMapping("/update_userinfo")
    public AppResult updateUserinfo(HttpServletRequest request,
                                    @RequestBody @NonNull Userinfo userinfo) {
        //1.非空校验
        if(userinfo.getBirthday() == null && userinfo.getEmail() == null &&
        userinfo.getGender() == null && userinfo.getCompany() == null &&
        userinfo.getEducation() == null && userinfo.getGraduateYear() == null &&
        userinfo.getLocation() == null && userinfo.getPhoneNumber() == null &&
        userinfo.getPosition() == null && userinfo.getSchool() == null &&
        userinfo.getWorkYear() == null) {
            return AppResult.fail(CodeMsg.FAIL_NULL_USER_UPDATE);
        }
        //2.准备数据
        String token = request.getHeader(HeaderConstants.TOKEN);
        String userJson = redisTemplate.opsForValue().get(RedisConstants.TOKEN + token);
        User redisUser = objectMapper.readValue(userJson, User.class);
        userinfo.setUsername(redisUser.getUsername());
        //3.修改
        userService.updateUserinfo(userinfo);
        return AppResult.success();
    }

}
